//
//  MyReaderController.swift
//  eBooks
//
//  Created by JunMing on 2019/12/6.
//  Copyright © 2019 赵俊明. All rights reserved.
//

import UIKit
import YYKit
import RxCocoa
import RxSwift
import FolioReaderKit

class MyReaderController: EbookBaseController {
    fileprivate var tableView:UITableView!
    fileprivate lazy var bag:DisposeBag = DisposeBag()
    fileprivate var dataSource:[Model]!
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "share")?.origin, style: UIBarButtonItem.Style.done, target: self, action: #selector(shareAll))
        setupTableView()
        let vModel = MyReaderModel()
        vModel.modelObserable.asObservable().subscribe(onNext: { (data:[Model]) in
            self.dataSource = data
            self.tableView.reloadData()
        }).disposed(by: bag)
        registEventAction()
        MobClick.event("set_myRead")
    }
    
    func setupTableView() {
        tableView = UITableView(frame: view.bounds, style: .grouped)
        tableView.register(MyReaderCell.self, forCellReuseIdentifier: "cellid")
        tableView.delegate = self
        tableView.dataSource = self
        tableView.sectionHeaderHeight = 0;
        tableView.sectionFooterHeight = 0;
        tableView.backgroundColor = view.backgroundColor
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.width.height.equalTo(view)
        }
    }
    
    @objc func shareAll() {
        MobClick.event("set_myRead_topShare")
        var totalTime = 0
        let startTime = dataSource.first?.date?.formatTspString("yyyy年MM月dd日")
        let count = dataSource.count
        var title = ""
        if let fName = dataSource.first?.fullTitle(),let lName = dataSource.last?.fullTitle(), count > 1 {
            title = fName+","+lName
        }
        
        for model in dataSource {
            totalTime += model.totalTime
        }
        
        let content =  "从\(startTime!)开始，用了\(totalTime.currentTime)，共读了\(title)等\(count)本书。读一本好书，就是和许多高尚的人谈话！"
        
        let item = SheetItem(title: "我读过的书")
        item.subTitle = "Epub 阅读"
        item.icon = UIImage(named: "share_bkg5")
        item.topLogo = UIImage(named: "defaulticon")
        item.attrStr = content.attribute(UIFont.regular(15)!, alignment:.center, space:1)
        item.className = "BookInfoShare"
        let manager = SheetManager(superView: self.view, item: item)
        manager.update()
    }
    
    func registEventAction() {
        registerEvent(eventName: kShowPanelVCEventName, block: { model in
            let newModel = model as! Model
            let item = SheetItem(title: newModel.title()!)
            item.topLogo = UIImage(named: "share_bkg2")
            item.icon = UIImage(named: "share_bkg2")
            item.className = "BookInfoShare"
            UIImageView().setImageWith(URL(string: newModel.coverurl()), placeholder: nil, options: .progressiveBlur, completion: { (image, _, _, _, _) in
                item.topLogo = image
            })
            
            let sTime = newModel.date?.formatTspString("yyyy年MM月dd日")
            let tTime = newModel.totalTime.currentTime
            let content =  "我从\(sTime!)开始阅读\(newModel.fullTitle()!)，总共花了\(tTime)时间，\(newModel.rateDesc())！\n🎉阅读让人生更精彩🎉"
            
            if let author = newModel.author { item.subTitle = "by "+author}
            item.attrStr = content.attribute(UIFont.regular(15)!, alignment:.center, space:1)
            item.eventName = kSharePanelVCEventName
            let manager = SheetManager(superView: self.view, item: item)
            manager.update()
        }, next: false)
        
        registerEvent(eventName: kHidePanelVCEventName, block: { panelVC in
            print(kHidePanelVCEventName)
        }, next: false)
        
        registerEvent(eventName: kSharePanelVCEventName, block: { object in
            print(kSharePanelVCEventName)
        }, next: false)
        
        registerEvent(eventName: kEBookShareActionEventName, block: { object in
            let image = object as! UIImage
            self.shareImageToFriends(shareID: "epub 阅读器", image: image, completionHandler: { (type, status) in
                print("分享成功")
                print(kEBookShareActionEventName)
            })
        }, next: false)
    }
    
}

extension MyReaderController:UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "cellid")
        if cell == nil {
            cell = SettingCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "cellid")
        }
        let cellNew = cell as! MyReaderCell
        cellNew.model = dataSource[indexPath.row]
        return cellNew
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        openEpubBooks(indexPath: indexPath)
    }
    
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "删除"
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == UITableViewCell.EditingStyle.delete {
            dataSource.remove(at: indexPath.row)
            let model = dataSource[indexPath.row]
            // 如果本地已删除，直接删除记录，如果未删除，时间设置为0
            if model.isdel {
                SQLHelper.share.deleteLocalDB(model)
            }else {
                model.totalTime = 0
                SQLHelper.share.updateLocalDB(model, type:.totalTime)
            }
            tableView.reloadData()
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 64
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 250
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        var headView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "header")
        if headView == nil {
            headView = MyReaderHeaderView(reuseIdentifier: "header")
        }
        let newView = headView as! MyReaderHeaderView
        newView.dataSource = dataSource
        return headView
    }
    
    func openEpubBooks(indexPath:IndexPath) {
        let model = dataSource[indexPath.row]
        if !model.isdel {
            openEpubBooks(model)
        }
    }
}

// MARK: cell MyReaderCell
class MyReaderCell: UITableViewCell {
    var downloadFails:((_ model:Model) -> Void)?
    fileprivate var cover = ImageLayerView()
    fileprivate var bookName = UILabel()
    fileprivate var dateL = UILabel()
    fileprivate var totalTime = UILabel()
    fileprivate var deleted = UILabel()
    fileprivate var detail = UIButton(type: .system)
    var model:Model! {
        willSet(newValue) {
            bookName.text = newValue!.title()
            dateL.text = newValue!.date?.formatTspString("yyyy年MM月dd日 HH:mm")
            totalTime.text = newValue.totalTime.currentTime
            cover.loadImage(url: newValue!.coverurl())
            if newValue!.isdel { deleted.text = "已删除" }
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = UIColor.white
        contentView.addSubview(cover)
        bookName.configLabel(font: UIFont.medium(15), tColor: UIColor.black)
        contentView.addSubview(bookName)
        
        totalTime.configLabel(font: UIFont.medium(15), tColor: UIColor.black)
        contentView.addSubview(totalTime)
        
        dateL.configLabel(font: UIFont.regular(13))
        contentView.addSubview(dateL)
        
        deleted.configLabel(font: UIFont.regular(13), tColor: UIColor.red)
        contentView.addSubview(deleted)
        
        detail.setImage(UIImage(named: "moreicon")?.origin, for: .normal)
        detail.addTarget(self, action: #selector(shareAction), for: .touchUpInside)
        contentView.addSubview(detail)
        
        layoutViews()
    }
    
    @objc func shareAction() {
        routerEvent(eventName: kShowPanelVCEventName, info: model)
        MobClick.event("set_myRead_cellShare")
    }
    
    func layoutViews() {
        cover.snp.makeConstraints { (make) in
            make.left.equalTo(contentView).offset(10)
            make.width.equalTo(44)
            make.top.equalTo(contentView).offset(5)
            make.bottom.equalTo(contentView).offset(-5)
        }
        
        bookName.snp.makeConstraints { (make) in
            make.left.equalTo(cover.snp_right).offset(10)
            make.top.equalTo(cover.snp_top).offset(5)
            make.right.equalTo(contentView.snp_right).offset(-60)
            make.height.equalTo(20)
        }
        
        dateL.snp.makeConstraints { (make) in
            make.left.equalTo(cover.snp_right).offset(10)
            make.bottom.equalTo(cover.snp_bottom).offset(-5)
            make.height.equalTo(20)
        }
        
        deleted.snp.makeConstraints { (make) in
            make.left.equalTo(dateL.snp_right).offset(10)
            make.bottom.equalTo(dateL.snp_bottom)
            make.height.equalTo(20)
        }
        
        totalTime.snp.makeConstraints { (make) in
            make.top.equalTo(snp.top).offset(3)
            make.right.equalTo(contentView.snp_right).offset(-10)
            make.height.equalTo(30)
        }
        
        detail.snp.makeConstraints { (make) in
            make.right.equalTo(contentView.snp_right).offset(-10)
            make.bottom.equalTo(snp.bottom).offset(-3)
            make.width.height.equalTo(30)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK: 头部统计表单 MyReaderHeaderView
import Charts
class MyReaderHeaderView: UITableViewHeaderFooterView {
    fileprivate var bookName = UILabel()
    var pieChartView:PieChartView = PieChartView()
    open var dataSource = [Model]() {
        willSet {drawPieChartView(newValue)}
    }
    
    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
        contentView.addSubview(pieChartView)
        pieChartView.snp.makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
      
        pieChartView.setExtraOffsets(left: 0, top: 0, right: 0, bottom: 20)
        pieChartView.usePercentValuesEnabled = true  //转化为百分比
        pieChartView.drawEntryLabelsEnabled = true //显示区块文本
        pieChartView.entryLabelFont = UIFont.systemFont(ofSize: 10) //区块文本的字体
        pieChartView.entryLabelColor = UIColor.white
        pieChartView.drawSlicesUnderHoleEnabled = true
        
        //图例样式设置
        pieChartView.legend.maxSizePercent = 1  //图例的占比
        pieChartView.legend.form = .square //图示：原、方、线
        pieChartView.legend.formSize = 5 //图示大小
        pieChartView.legend.formToTextSpace = 4 //文本间隔
        pieChartView.legend.font = UIFont.systemFont(ofSize: 8)
        pieChartView.legend.textColor = UIColor.black
        pieChartView.legend.horizontalAlignment = .left
        pieChartView.legend.verticalAlignment = .top
        pieChartView.animate(xAxisDuration: 0.5, yAxisDuration: 0.5, easingOption: .easeInBack)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func drawPieChartView(_ models:[Model]) {
        var yVals = [PieChartDataEntry]()
        var colors = [UIColor]()
        for model in models {
            var title = ""
            if let name = model.title() {
                if name.count > 2 {
                    title = String(name.prefix(2))+".."
                }else {
                    title = name
                }
            }
            let entry = PieChartDataEntry(value: Double(model.totalTime),label: title)
            yVals.append(entry)
            colors.append(UIColor.randColor)
        }
        
        let dataSet = PieChartDataSet(entries: yVals,label: "")
        dataSet.colors = colors //设置名称和数据的位置 都在内就没有折线了
        dataSet.xValuePosition = .insideSlice
        dataSet.yValuePosition = .outsideSlice
        dataSet.sliceSpace = 1 //相邻块的距离
        dataSet.selectionShift = 6.66  //选中放大半径
        
        // 指示折线样式
        // 折线中第一段起始位置相对于区块的偏移量, 数值越大, 折线距离区块越远
        dataSet.valueLinePart1OffsetPercentage = 0.8
        dataSet.valueLinePart1Length = 0.8 //折线中第一段长度占比
        dataSet.valueLinePart2Length = 0.4 //折线中第二段长度最大占比
        dataSet.valueLineWidth = 1 //折线的粗细
        dataSet.valueLineColor = UIColor.brown //折线颜色
        let data = PieChartData(dataSets: [dataSet])
        data.setValueFont(UIFont.systemFont(ofSize: 8.0))
        data.setValueTextColor(UIColor.randColor)
        pieChartView.data = data
    }
}

// MARK: 展示详细内容控制器 DetailContent
class DetailContent: UIViewController {
    private var close = UIButton(type: .system)
    override func viewDidLoad() {
        super.viewDidLoad()
        close.setImage(UIImage(named: "navbar_close_icon_black")?.origin, for: .normal)
        close.addTarget(self, action: #selector(closeAction), for: .touchUpInside)
        view.addSubview(close)
        view.backgroundColor = UIColor.randColor
        close.snp.makeConstraints { (make) in
            make.right.equalTo(view.snp_right).offset(-10)
            make.top.equalTo(view).offset(7)
            make.height.width.equalTo(44)
        }
    }
    
    @objc func closeAction() {
        if let vc = self.parent {
            routerEvent(eventName: kHidePanelVCEventName, info: vc)
        }
    }
}

//if
//    let currentPageNumber = self.folioReader.readerCenter?.currentPageNumber,
//    let reference = self.book.spine.spineReferences[safe: currentPageNumber - 1],
//    (tocReference.resource != nil) {
//    let resource = reference.resource
//    cell.indexLabel?.textColor = (tocReference.resource == resource ? self.readerConfig.menuTextColorSelected : self.readerConfig.menuTextColor)
//}
